﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Telerik.Web.UI;
using System.Web.UI.HtmlControls;
using Runda.CMS.Common.Utility;
using System.Data;

namespace Runda.CMS.Portal.Budget
{
    public partial class SalesBudgetEdit : System.Web.UI.Page
    {
        public Guid? BudgetID
        {
            get {
                if (ViewState["BudgetID"] == null) return null;
                return new Guid(ViewState["BudgetID"].ToString()); 
            }
            set { ViewState["BudgetID"] = value; }
        }

        public Guid AssistID
        {
            get
            {
                if (ViewState["AssistID"] != null)
                {
                    return new Guid(ViewState["AssistID"].ToString());
                }
                else if (Request.QueryString["AssistID"] != null)
                {
                    ViewState["AssistID"] = Request.QueryString["AssistID"];
                }

                return new Guid(ViewState["AssistID"].ToString());
            }
            set { ViewState["AssistID"] = value; }
        }

        public int BudgetYear
        {
            get { return Convert.ToInt32(Request.QueryString["BudgetYear"]); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["Type"] != null)
                {
                    if (Request.QueryString["Type"] == "1")
                    {
                        txtInstrumentModel.Enabled = false;
                        txtQ1Count.Enabled = false;
                        txtQ2Count.Enabled = false;
                        txtQ3Count.Enabled = false;
                        txtQ4Count.Enabled = false;
                        txtQ1Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#DBDBDB");
                        txtQ2Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#DBDBDB");
                        txtQ3Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#DBDBDB");
                        txtQ4Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#DBDBDB");
                        txtPrice.Attributes.CssStyle.Add(HtmlTextWriterStyle.Display, "none");
                        lblprice.Attributes.CssStyle.Add(HtmlTextWriterStyle.Display, "none");
                        lblproduct.Attributes.CssStyle.Add(HtmlTextWriterStyle.Display, "none");
                        txtInstrumentModel.Attributes.CssStyle.Add(HtmlTextWriterStyle.Display, "none");
                    }
                    else
                    {
                        txtInstrumentModel.Enabled = true;
                        txtQ1Count.Enabled = true;
                        txtQ2Count.Enabled = true;
                        txtQ3Count.Enabled = true;
                        txtQ4Count.Enabled = true;
                        txtQ1Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
                        txtQ2Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
                        txtQ3Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
                        txtQ4Count.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
                    }
                    hidType.Value = Request.QueryString["Type"].ToString();

                }
                if (Request.QueryString["BudgetID"] == null)//新增状态
                { 
                    LoadRadTree("",Request.QueryString["Type"]);
                }
                else //修改状态
                {
                    BudgetID = new Guid(Request.QueryString["BudgetID"]);
                    InitializeFromData();
                }
                if (Request.QueryString["customername"] != null)
                {
                    lblCustomername.Text = Request.QueryString["customername"].ToString();
                }
            }
        }

        private void InitializeFromData()
        {
            BudgetBll bll = new BudgetBll();
            BGSalesBudgetsEntity entity = bll.Get<BGSalesBudgetsEntity>(BudgetID.Value);
            if (entity != null)
            {
                LoadRadTree(entity.ProductCategoryID.ToString(),entity.productType);
                //txtInstrumentModel.Text = entity.productModel;

                Button1_Click(null, null);
                txtInstrumentModel.SelectedValue = entity.productModel;
                txtPrice.Text = entity.unitPrice.ToString();
                txtRemark.Text = entity.Memo;
                txtQ1Count.Text = entity.Q1quantity.ToString();
                txtQ1Amount.Text = entity.Q1Amount.ToString();
                txtQ2Count.Text = entity.Q2quantity.ToString();
                txtQ2Amount.Text = entity.Q2Amount.ToString();
                txtQ3Count.Text = entity.Q3quantity.ToString();
                txtQ3Amount.Text = entity.Q3Amount.ToString();
                txtQ4Count.Text = entity.Q4quantity.ToString();
                txtQ4Amount.Text = entity.Q4Amount.ToString();
                txtTotalCount.Text = entity.TotalQuantity.ToString();
                txtTotalAmount.Text = entity.TotalAmount.ToString();
                hidSalesAgencyID.Value = entity.SalesAgencyID.ToString();

                CtrtCustomerEntity CustomerEnt = bll.Get<CtrtCustomerEntity>(entity.SalesAgencyID);
                if (CustomerEnt != null)
                    txtCustomer.Text = CustomerEnt.CustomerName;
                if (entity.SalesAgencyIsTrue == "Y")
                    this.chbSaleAgencyIsTrue.Checked = true;

                AssistID = entity.AssistID;

                List<BGSalesBudgetsByMonthEntity> list = bll.GetAll<BGSalesBudgetsByMonthEntity>(" and BudgetID='" + BudgetID.Value + "'", " order by BudgetMonth");
                gridItems.DataSource = list;
                gridItems.DataBind();
            }
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            if (!CheckData()) { return; }
            BudgetBll bll = new BudgetBll();
            BGSalesBudgetsEntity entity = null;
            if (BudgetID.HasValue)
            {
                entity = bll.Get<BGSalesBudgetsEntity>(BudgetID.Value);
            }
            else
            {
                entity = new BGSalesBudgetsEntity();
                entity.AssistID = AssistID;
                entity.BudgetID = Guid.NewGuid();
                entity.productType = Request.QueryString["Type"];

                BudgetID = entity.BudgetID;
            }
            entity.salesBudgetType = "1"; //1,销售预算2,投放预算
            if (Text1.Value != "")
            {
                Guid ID = new Guid(Text1.Value);
                CtrtInstrumentCategoryEntity instrmentEntity = bll.Get<CtrtInstrumentCategoryEntity>(ID);
                if (instrmentEntity != null)
                {
                    entity.productCategoryCode = instrmentEntity.categoryCode;
                    entity.ProductCategoryID = instrmentEntity.categoryGUID;
                }
            }

            if (hidSalesAgencyID.Value != "")
            {
                entity.SalesAgencyID = new Guid(hidSalesAgencyID.Value);
                entity.SalesAgencyIsTrue = chbSaleAgencyIsTrue.Checked ? "Y" : "N";
            }
            entity.unitPrice = txtPrice.Text == "" ? 0 : Convert.ToDecimal(txtPrice.Text.Trim());
            entity.TotalAmount = txtTotalAmount.Text == "" ? 0 : Convert.ToDecimal(txtTotalAmount.Text.Trim());

            entity.Q1quantity = txtQ1Count.Text == "" ? 0 : Convert.ToDecimal(txtQ1Count.Text);
            entity.Q1Amount = txtQ1Amount.Text == "" ? 0 : Convert.ToDecimal(txtQ1Amount.Text);

            entity.Q2quantity = txtQ2Count.Text == "" ? 0 : Convert.ToDecimal(txtQ2Count.Text);
            entity.Q2Amount = txtQ2Amount.Text == "" ? 0 : Convert.ToDecimal(txtQ2Amount.Text);

            entity.Q3quantity = txtQ3Count.Text == "" ? 0 : Convert.ToDecimal(txtQ3Count.Text);
            entity.Q3Amount = txtQ3Amount.Text == "" ? 0 : Convert.ToDecimal(txtQ3Amount.Text);

            entity.Q4quantity = txtQ4Count.Text == "" ? 0 : Convert.ToDecimal(txtQ4Count.Text);
            entity.Q4Amount = txtQ4Amount.Text == "" ? 0 : Convert.ToDecimal(txtQ4Amount.Text);

            entity.BudgetYear = BudgetYear.ToString();
            entity.productModel = txtInstrumentModel.SelectedValue.ToString();
            entity.Memo = txtRemark.Text;
            List<BGSalesBudgetsByMonthEntity> list = GetBudgetByMonthManual();
            decimal Quantity = 0;
            decimal Amount = 0;
            foreach (BGSalesBudgetsByMonthEntity ent in list)
            {
                Quantity += ent.quantity;
                Amount += ent.Amount;
                ent.BudgetID = BudgetID.Value;

            }
            entity.TotalAmount = Amount;
            entity.TotalQuantity = Quantity;

            bll.SaveSalesBudgets(entity, list);

            if (Request.QueryString["Type"] == "1")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功!');window.close();window.opener.document.getElementById('ctl00_cphBody_btnRefersh1').click();", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功!');window.close();window.opener.document.getElementById('ctl00_cphBody_btnRefersh3').click();", true);
            }
        }

        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            List<BGSalesBudgetsByMonthEntity> list = GetBudgetByMonthAuto();
            //rebind
            gridItems.DataSource = list;
            gridItems.DataBind();

            decimal Quantity = 0;
            decimal Amount = 0; 
            foreach (BGSalesBudgetsByMonthEntity entity in list)
            {
                Quantity += entity.quantity;
                Amount += entity.Amount;
           
            }

            txtTotalCount.Text = Quantity.ToString();
            txtTotalAmount.Text = Amount.ToString(); 
        }

  
        public List<BGSalesBudgetsByMonthEntity> GetBudgetByMonthAuto()
        {
            List<BGSalesBudgetsByMonthEntity> list = new List<BGSalesBudgetsByMonthEntity>();

            BGSalesBudgetsByMonthEntity entity = null;

            if (hidType.Value == "2")  //销售仪器预算
            {
                for (int i = 1; i < 13; i++)
                {
                    entity = new BGSalesBudgetsByMonthEntity();
                    entity.MonthBugetID = Guid.NewGuid();
                    entity.AssistID = AssistID;
                    entity.BudgetMonth = BudgetYear + i.ToString().PadLeft(2, '0');
                    entity.quantity = 0;

                    entity.Amount = 0;
                    list.Add(entity);
                }
            }
            else //试剂预算
            {
                for (int i = 1; i < 4; i++)
                {
                    entity = new BGSalesBudgetsByMonthEntity();
                    entity.MonthBugetID = Guid.NewGuid();
                    entity.AssistID = AssistID;
                    entity.BudgetMonth = BudgetYear + i.ToString().PadLeft(2, '0');
                    entity.quantity = 0;

                    decimal Amount = string.IsNullOrEmpty(txtQ1Amount.Text.Trim()) ? 0 : Convert.ToDecimal(txtQ1Amount.Text.Trim());
                    if (i == 3) { entity.Amount = Amount - Math.Round(Amount / 3, 2) * 2; }
                    else { entity.Amount = Math.Round(Amount / 3, 2); }
                   
                    list.Add(entity);
                }
                for (int i = 4; i < 7; i++)
                {
                    entity = new BGSalesBudgetsByMonthEntity();
                    entity.MonthBugetID = Guid.NewGuid();
                    //entity.BudgetID = BudgetID.Value;
                    entity.AssistID = AssistID;
                    entity.BudgetMonth = BudgetYear + i.ToString().PadLeft(2, '0');
                    entity.quantity = 0;

                    decimal Amount = string.IsNullOrEmpty(txtQ2Amount.Text.Trim()) ? 0 : Convert.ToDecimal(txtQ2Amount.Text.Trim());
                    if (i == 6) { entity.Amount = Amount - Math.Round(Amount / 3, 2) * 2; }
                    else { entity.Amount = Math.Round(Amount / 3, 2); }

                    list.Add(entity);
                }
                for (int i = 7; i < 10; i++)
                {
                    entity = new BGSalesBudgetsByMonthEntity();
                    entity.MonthBugetID = Guid.NewGuid();
                    //entity.BudgetID = BudgetID.Value;
                    entity.AssistID = AssistID;
                    entity.BudgetMonth = BudgetYear + i.ToString().PadLeft(2, '0');
                    entity.quantity = 0;

                    decimal Amount = string.IsNullOrEmpty(txtQ3Amount.Text.Trim()) ? 0 : Convert.ToDecimal(txtQ3Amount.Text.Trim());
                    if (i == 9) { entity.Amount = Amount - Math.Round(Amount / 3, 2) * 2; }
                    else { entity.Amount = Math.Round(Amount / 3, 2); }
                    list.Add(entity);
                }
                for (int i = 10; i < 13; i++)
                {
                    entity = new BGSalesBudgetsByMonthEntity();
                    entity.MonthBugetID = Guid.NewGuid();
                    //entity.BudgetID = BudgetID.Value;
                    entity.AssistID = AssistID;
                    entity.BudgetMonth = BudgetYear + i.ToString().PadLeft(2, '0');
                    entity.quantity = 0;

                    decimal Amount = string.IsNullOrEmpty(txtQ4Amount.Text.Trim()) ? 0 : Convert.ToDecimal(txtQ4Amount.Text.Trim());
                    if (i == 12) { entity.Amount = Amount - Math.Round(Amount / 3, 2) * 2; }
                    else { entity.Amount = Math.Round(Amount / 3, 2); }
                    list.Add(entity);
                }
            }
            return list;
        }

        public List<BGSalesBudgetsByMonthEntity> GetBudgetByMonthManual()
        {
            List<BGSalesBudgetsByMonthEntity> list = new List<BGSalesBudgetsByMonthEntity>();
            if (gridItems.Items.Count > 0)
            {
                BGSalesBudgetsByMonthEntity entity = null;
                foreach (Telerik.WebControls.GridDataItem item in gridItems.Items)
                {
                    if (item.ItemType == Telerik.WebControls.GridItemType.Item || item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
                    {
                        TextBox txtBudgetMonth = item.FindControl("txtBudgetMonth") as TextBox;
                        TextBox txtCount = item.FindControl("txtCount") as TextBox;
                        TextBox txtAmount = item.FindControl("txtAmount") as TextBox;

                        entity = new BGSalesBudgetsByMonthEntity();
                        entity.MonthBugetID = Guid.NewGuid();
                        //entity.BudgetID = BudgetID.Value;
                        entity.AssistID = AssistID;
                        entity.BudgetMonth = txtBudgetMonth.Text;
                        //decimal Quantity = string.IsNullOrEmpty(txtQ4Count.Text.Trim()) ? 0 : Convert.ToDecimal(txtQ4Count.Text.Trim());
                        decimal Quantity = 0;
                        decimal.TryParse(txtQ4Count.Text.Trim(), out Quantity);

                        entity.quantity = Quantity;

                        //decimal Amount = string.IsNullOrEmpty(txtQ4Amount.Text.Trim()) ? 0 : Convert.ToDecimal(txtQ4Amount.Text.Trim());
                        decimal Amount = 0;
                        decimal.TryParse(txtAmount.Text.Trim(), out Amount);
                        entity.Amount = Amount;
                        list.Add(entity);
                    }
                }
            }
            else
            {
                list = GetBudgetByMonthAuto();
            }

            return list;
        }

        private Boolean CheckData()
        {
            Boolean rtn = true;
            if (gridItems.Items.Count > 0)
            {
                decimal Q1Amount = 0;
                decimal Q2Amount = 0;
                decimal Q3Amount = 0;
                decimal Q4Amount = 0;
                decimal Amount = 0;
                int Q1quantity = 0;
                int Q2quantity = 0;
                int Q3quantity = 0;
                int Q4quantity = 0;
                int quantity = 0;
                int Q1quantityTmp = 0;
                int Q2quantityTmp = 0;
                int Q3quantityTmp = 0;
                int Q4quantityTmp = 0;
                decimal Q1AmountTmp = 0;
                decimal Q2AmountTmp = 0;
                decimal Q3AmountTmp = 0;
                decimal Q4AmountTmp = 0;
                

                foreach (Telerik.WebControls.GridDataItem item in gridItems.Items)
                {
                    if (item.ItemType == Telerik.WebControls.GridItemType.Item || item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
                    {
                        TextBox txtBudgetMonth = item.FindControl("txtBudgetMonth") as TextBox;
                        TextBox txtCount = item.FindControl("txtCount") as TextBox;
                        TextBox txtAmount = item.FindControl("txtAmount") as TextBox;

                        if (item.RowIndex <= 4)
                        {
                            if (int.TryParse(txtCount.Text.Trim(), out quantity)) { Q1quantity += quantity; }
                            if (decimal.TryParse(txtAmount.Text.Trim(), out Amount)) { Q1Amount += Amount; }
                        }

                        if (item.RowIndex <= 7 && item.RowIndex > 4)
                        {
                            if (int.TryParse(txtCount.Text.Trim(), out quantity)) { Q2quantity += quantity; }
                            if (decimal.TryParse(txtAmount.Text.Trim(), out Amount)) { Q2Amount += Amount; }
                        }
                        if (item.RowIndex <= 10 && item.RowIndex > 7)
                        {
                            if (int.TryParse(txtCount.Text.Trim(), out quantity)) { Q3quantity += quantity; }
                            if (decimal.TryParse(txtAmount.Text.Trim(), out Amount)) { Q3Amount += Amount; }
                        }

                        if (item.RowIndex <= 13 && item.RowIndex > 10)
                        {
                            if (int.TryParse(txtCount.Text.Trim(), out quantity)) { Q4quantity += quantity; }
                            if (decimal.TryParse(txtAmount.Text.Trim(), out Amount)) { Q4Amount += Amount; }
                        }


                    }
                }

                int.TryParse(txtQ1Count.Text.Trim(), out Q1quantityTmp);
                int.TryParse(txtQ2Count.Text.Trim(), out Q2quantityTmp);
                int.TryParse(txtQ3Count.Text.Trim(), out Q3quantityTmp);
                int.TryParse(txtQ4Count.Text.Trim(), out Q4quantityTmp);
                decimal.TryParse(txtQ1Amount.Text.Trim(), out Q1AmountTmp);
                decimal.TryParse(txtQ2Amount.Text.Trim(), out Q2AmountTmp);
                decimal.TryParse(txtQ3Amount.Text.Trim(), out Q3AmountTmp);
                decimal.TryParse(txtQ4Amount.Text.Trim(), out Q4AmountTmp);

                if (Q1quantityTmp != Q1quantity) 
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('第一季度仪器销售数量有误!');", true);
                    rtn = false; }
                if (Q2quantityTmp != Q2quantity)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('第二季度仪器销售数量有误!');", true);
                    rtn = false;
                }
                if (Q3quantityTmp != Q3quantity)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('第三季度仪器销售数量有误!');", true);
                    rtn = false;
                }
                if (Q4quantityTmp != Q4quantity)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('第四季度仪器销售数量有误!');", true);
                    rtn = false;
                }

                if (Q1AmountTmp != Q1Amount)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('第一季度仪器试剂销售金额有误!');", true);
                    rtn = false;
                }

            }
            else { rtn = false; }

            return rtn;
        }

        private void LoadRadTree(string categoryGUID,string Type)
        {
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            if (Type == "1")
            { 
                dt =bll.GetInstrumentCategory(" and SUBSTRING(categorycode,1,2) = '01' "); 
            }
            else
            {
                dt = bll.GetInstrumentCategory(" and SUBSTRING(categorycode,1,2) = '02' ");
            }

            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryGUID != "")
            {
                Text1.Value = categoryGUID;
                txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();

            List<WsmInstrumentInfoEntity> list = bll.GetInstrumentEntities(new Guid(Text1.Value));
            this.txtInstrumentModel.DataSource = list;
            txtInstrumentModel.DataValueField = "InstrumentName";
            txtInstrumentModel.DataTextField = "InstrumentName";
            txtInstrumentModel.DataBind();
            txtInstrumentModel.Items.Add(new ListItem("   ", ""));
            txtInstrumentModel.SelectedValue = "";
        }

    }
}
